package com.sdy.healthcode.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.MapUtil;
import com.sdy.healthcode.biz.constants.Constants;
import com.sdy.healthcode.biz.dto.DoctorManDTO;
import com.sdy.healthcode.biz.dto.DoctorManagerDTO;
import com.sdy.healthcode.biz.model.ExpertsInformation;
import com.sdy.healthcode.biz.service.ExpertsInformationService;
import com.sdy.healthcode.biz.service.ExpertsScheduleDailyService;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.springframework.util.StringUtils.isEmpty;



/**
 * 医生管理 前端控制器
 *
 * @author lx
 * @since 2020-03-09
 */
@Slf4j
@RestController
@RequestMapping("/doctorManage")
@Api(tags = "医生管理")
public class DoctorManageController extends BaseController {

    @Autowired
    private ExpertsInformationService expertsInformationService;
    @Autowired
    private ExpertsScheduleDailyService expertsScheduleDailyService;
    @Autowired
    private FileService fileService;

    @GetMapping("/doctorManageShowPage")
    @ApiOperation(value = "医生管理展示界面")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(dataType = "String", name = "name", value = "医生姓名"),
            @ApiImplicitParam(dataType = "String", name = "introduction", value = "简介"),
            @ApiImplicitParam(dataType = "String", name = "photoPath", value = "照片路径"),
            @ApiImplicitParam(dataType = "String", name = "department", value = "所在诊室"),
            @ApiImplicitParam(dataType = "String", name = "phoneNumber", value = "手机号"),
            @ApiImplicitParam(dataType = "Integer", name = "professionalTitle", value = "职称 0.初级 1.中级 2.副高级 3.正高级"),
            @ApiImplicitParam(dataType = "Integer", name = "suspendService", value = "状态 1、可预约 2、长期停诊 3、停诊不显示 4、临时停诊 null、全部"),
            @ApiImplicitParam(dataType = "Integer", name = "visitPrice", value = "专家诊金"),
    })
    public Response doctorManageShowPage(String name, Integer suspendService , Page<DoctorManagerDTO.Doctor> page) throws UnsupportedEncodingException {
        if (!isEmpty(name)) {
            name = URLDecoder.decode(name, StandardCharsets.UTF_8.name());
        }
        Map<String, Object> map = new HashMap<>();
        if (!isEmpty(name)) {
            map.put("name", name);
        }
        if (suspendService != null) {
            map.put("suspend_service", suspendService);
        }
        IPage<DoctorManagerDTO.Doctor> result = expertsInformationService.pageDoctorManage(page, map);
        return Response.success(result);
    }

    @GetMapping("/doctorManageShowOnePage")
    @ApiOperation(value = "医生管理详情展示")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "医生id"),
    })
    public Response doctorManageShowOnePage(Integer id){
        if (isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        ExpertsInformation expertsInformation = expertsInformationService.getById(id);
        return Response.success(expertsInformation);
    }

    @GetMapping("/deleteDoctorMess")
    @ApiOperation(value = "医生管理删除")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "医生id"),
    })
    public Response deleteDoctorMess(Integer id){
        if (isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        if (expertsScheduleDailyService.isDoctorScheduled(id)) {
            return Response.error("已经生成医生排班，禁止删除");
        }
        expertsInformationService.deldteByDocId(id);
        return Response.success();
    }

    @PostMapping("/updateDoctorMess")
    @ApiOperation(value = "修改医生管理信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "医生id"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "医生姓名"),
            @ApiImplicitParam(dataType = "String", name = "introduction", value = "简介"),
            @ApiImplicitParam(dataType = "String", name = "photoPath", value = "照片路径"),
            @ApiImplicitParam(dataType = "Integer", name = "departmentId", value = "所在诊室"),
            @ApiImplicitParam(dataType = "String", name = "phoneNumber", value = "手机号"),
            @ApiImplicitParam(dataType = "Integer", name = "professionalTitle", value = "职称 0.初级 1.中级 2.副高级 3.正高级"),
            @ApiImplicitParam(dataType = "Integer", name = "suspendService", value = "状态 1、可预约 2、长期停诊 3、停诊不显示 4、临时停诊"),
            @ApiImplicitParam(dataType = "Integer", name = "visitPrice", value = "专家诊金"),
            @ApiImplicitParam(dataType = "Integer", name = "replaceDoctor", value = "替诊医生"),
            @ApiImplicitParam(dataType = "Integer", name = "action", value = "1-设置替诊 2-取消替诊"),

    })
    public Response updateDoctorMess(@RequestBody ExpertsInformation expertsInformation) throws BizException, IOException {
        if (isEmpty(expertsInformation.getId()) || isEmpty(expertsInformation.getDepartmentId()) || isEmpty(expertsInformation.getName())
                || isEmpty(expertsInformation.getSuspendService()) || isEmpty(expertsInformation.getPhoneNumber())
                || isEmpty(expertsInformation.getProfessionalTitle()) || isEmpty(expertsInformation.getVisitPrice())
        ) {
            return Response.error("必填信息不能为空");
        }
        if (expertsInformation.getId().equals(expertsInformation.getReplaceDoctor())) {
            return Response.error("替诊医生不能是自己");
        }
        Assert.isTrue(!expertsInformation.getPhoneNumber().matches(Constants.REGEX_PHONE), "手机号格式错误");
        expertsInformationService.updateDocMess(expertsInformation);
        return Response.success();
    }

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Response upload(MultipartFile file) throws Exception {
        Map<String, Object> result = new HashMap<>();
        FileObj fileObj = fileService.saveFile(file, "healthcode/doctor/photo");
        result.put("url", fileObj.getPath());
        return Response.success(result);
    }
    
    @GetMapping("/selectConsultingRoom")
    @ApiOperation(value = "查询诊室下的医生")
    public Response selectConsultingRoom(){
        IPage<DoctorManagerDTO.Doctor> roomAndDoctors = expertsInformationService.pageDoctorManage(new Page<>(1, 10000), Collections.emptyMap());
        Map<Integer, List<DoctorManagerDTO.Doctor>> map = MapUtil.collectionToMapList(roomAndDoctors.getRecords(), DoctorManagerDTO.Doctor::getDepartmentId);
        Map<Integer, String> deptMap = new HashMap<>();
        for (DoctorManagerDTO.Doctor record : roomAndDoctors.getRecords()) {
            deptMap.put(record.getDepartmentId(), record.getDepartment());
        }
        List<Object> options = new ArrayList<>();
        Set<Integer> strings2 = map.keySet();
        strings2.forEach(o->{
            Map<String, Object> jsonObject = new HashMap<>();
            jsonObject.put("name", deptMap.get(o));
            jsonObject.put("id", -o);
            List<DoctorManagerDTO.Doctor> strings3 = map.get(o);
            List<Object> jsonArray = new ArrayList<>();
            for (DoctorManagerDTO.Doctor s: strings3) {
                Map<String, Object> jsonObject1 = new HashMap<>();
                jsonObject1.put("name", s.getName());
                jsonObject1.put("id", s.getId());
                jsonArray.add(jsonObject1);
            }
            jsonObject.put("doctor",jsonArray);
            options.add(jsonObject);
        });
        return Response.success(options);
    }

    @PostMapping("/insertDoctorMess")
    @ApiOperation(value = "新增医生管理信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(dataType = "String", name = "name", value = "医生姓名"),
            @ApiImplicitParam(dataType = "String", name = "introduction", value = "简介"),
            @ApiImplicitParam(dataType = "String", name = "photoPath", value = "照片路径"),
            @ApiImplicitParam(dataType = "Integer", name = "departmentId", value = "所在诊室"),
            @ApiImplicitParam(dataType = "String", name = "phoneNumber", value = "手机号"),
            @ApiImplicitParam(dataType = "Integer", name = "professionalTitle", value = "职称 0.初级 1.中级 2.副高级 3.正高级"),
            @ApiImplicitParam(dataType = "Integer", name = "suspendService", value = "状态 1、可预约 2、长期停诊 3、停诊不显示 4、临时停诊"),
            @ApiImplicitParam(dataType = "Integer", name = "visitPrice", value = "专家诊金"),
            @ApiImplicitParam(dataType = "Integer", name = "replaceDoctor", value = "替诊医生"),
    })
    public Response insertDoctorMess(@RequestBody ExpertsInformation expertsInformation) throws BizException, IOException {
        if (isEmpty(expertsInformation.getDepartmentId()) || isEmpty(expertsInformation.getName()) ||
                isEmpty(expertsInformation.getSuspendService()) || isEmpty(expertsInformation.getPhoneNumber()) ||
                isEmpty(expertsInformation.getProfessionalTitle()) || isEmpty(expertsInformation.getVisitPrice())
        ) {
            return Response.error("必填信息不能为空");
        }
        Assert.isTrue(!expertsInformation.getPhoneNumber().matches(Constants.REGEX_PHONE), "手机号格式错误");
        expertsInformationService.saveDoctorMess(expertsInformation);
        return Response.success();
    }

    @GetMapping("/exportDoctorMess")
    @ApiOperation(value = "导出医生信息")
    public void exportDoctorMess(HttpServletResponse response, String name, Integer suspendService) throws IOException {
        if(!isEmpty(name)) {
            name = URLDecoder.decode(name, StandardCharsets.UTF_8.name());
        }
        String date = DateUtil.formatDate(new Date());
        List<DoctorManDTO> list = expertsInformationService.queryParmDoc(name, suspendService, null);
        for (DoctorManDTO exp : list) {
            if (exp.getSuspendService().equals("1")) {
                exp.setSuspendService("接诊");
            }
            if (exp.getSuspendService().equals("2")) {
                exp.setSuspendService("长期停诊");
            }
            if (exp.getSuspendService().equals("3")) {
                exp.setSuspendService("不接诊");
            }
            if (exp.getSuspendService().equals("4")) {
                exp.setSuspendService("临时停诊");
            }
            if (Objects.equals(exp.getProfessionalTitle(), "0")) {
                exp.setProfessionalTitle("初级");
            }
            if (Objects.equals(exp.getProfessionalTitle(), "1")) {
                exp.setProfessionalTitle("中级");
            }
            if (Objects.equals(exp.getProfessionalTitle(), "2")) {
                exp.setProfessionalTitle("副高级");
            }
            if (Objects.equals(exp.getProfessionalTitle(), "3")) {
                exp.setProfessionalTitle("正高级");
            }
        }
        String fileName = date + "医生信息表.xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        EasyExcel.write(response.getOutputStream(), DoctorManDTO.class).sheet("医生信息表").doWrite(list);
    }
    
    @PostMapping("/batchDoctorSettingState")
    @ApiOperation(value = "批量设置医生状态")
    public Response<Object> batchDoctorSettingState(@RequestBody Map<Integer, Set<Integer>> batchStateSettings) {
        expertsInformationService.batchDoctorSettingState(batchStateSettings);
        return Response.success();
    }

}